package net.sashag.nadlandroid;

import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.apps.analytics.easytracking.TrackedMapActivity;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.Extra;
import com.googlecode.androidannotations.annotations.ItemClick;
import com.googlecode.androidannotations.annotations.NoTitle;
import com.googlecode.androidannotations.annotations.OptionsItem;
import com.googlecode.androidannotations.annotations.OptionsMenu;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.ViewById;
import com.parse.ParseException;
import com.parse.ParseUser;

@EActivity(R.layout.aptdetails)
@OptionsMenu(R.menu.aptdetails_menu)
@NoTitle
public class ApartmentDetailsActivity extends TrackedMapActivity {
	
	@Bean protected FavoritesManager favoritesManager;
	
	@Extra("Apartment") protected Apartment apartment;
	
	@ViewById protected TextView txtUnpublished;
	@ViewById protected RatingBar rtgApartmentRating;
	@ViewById protected TextView txtNumRatings;
	@ViewById protected LinearLayout llPlaceholder;
	@ViewById protected TextView txtAddress;
	@ViewById protected TextView txtPrice;
	@ViewById protected TextView txtBedrooms;
	@ViewById protected TextView txtPhoneNumber;
	@ViewById protected TextView txtEmailAddress;
	@ViewById protected CheckBox chkAC;
	@ViewById protected CheckBox chkParking;
	@ViewById protected CheckBox chkLift;
	@ViewById protected TextView txtNotesLabel;
	@ViewById protected TextView txtNotes;
	@ViewById protected WebView webStreetView;
	@ViewById protected TextView txtPicturesLabel;
	@ViewById protected GridView grdPictures;

	private MapView mapApartment;
	private ImageGridAdapter picturesAdapter;
	private ApartmentRating rating;
	private ProgressDialog progress;
	
	@OptionsItem(R.id.add_to_favorites_menu_item)
	protected void onAddToFavoritesClicked() {
		ParseUser currentUser = ParseUser.getCurrentUser();
		favoritesManager.addToFavorites(apartment, currentUser);
		Toast.makeText(this, "Added to favorites", Toast.LENGTH_SHORT).show();
	}
	
	@OptionsItem(R.id.share_apartment_menu_item)
	protected void onShareApartmentClicked() {
		Intent sendIntent = new Intent(Intent.ACTION_SEND);
		sendIntent.putExtra(Intent.EXTRA_TEXT, apartment.formatForSend());
		sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Apartment from Nadlandroid");
		sendIntent.setType("text/plain");
		startActivity(sendIntent);
	}
	
	@OptionsItem(R.id.rate_apartment_menu_item)
	protected void onRateApartmentClicked() {
		AlertDialog.Builder ratingDialog = new AlertDialog.Builder(this);
		ratingDialog.setTitle("Rate This Apartment");
		ratingDialog.setMessage("Rate the apartment and provide some additional comments below.");
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		final RatingBar ratingBar = new RatingBar(this);
		ratingBar.setNumStars(5);
		ratingBar.setRating(5.0f);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		layoutParams.gravity = Gravity.CENTER;
		ratingBar.setLayoutParams(layoutParams);
		layout.addView(ratingBar);
		EditText textInput = new EditText(this);
		textInput.setLines(4);
		layout.addView(textInput);
		ratingDialog.setView(layout);
		ratingDialog.setPositiveButton("Submit", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (rating != null) { //It is possible that there's a connectivity problem and we can't submit ratings
					rating.addUserRating(ratingBar.getRating());
					updateRatingBar();
				}
				//TODO: What to do with the comments? Store them locally or on the server, display or not?
			}
		});
		ratingDialog.setNegativeButton("Cancel", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		ratingDialog.show();
	}
	
	@Background
	protected void resolveApartment(String apartmentId) {
		try {
			apartment = Apartment.fromId(apartmentId);
		} catch (ParseException e) {
			finishWithError("Error loading apartment: " + e.getMessage());
			return;
		}
		afterViews();
	}
	
	@UiThread
	protected void finishWithError(String error) {
		Toast.makeText(this, error, Toast.LENGTH_LONG).show();
		finish();
	}
	
	@AfterViews
	@UiThread
	protected void afterViews() {
		if (apartment == null) {
			//This was launched from an external intent using a URL. Resolve the apartment
			//and then come back here.
			progress = new ProgressDialog(this);
			progress.setTitle("Loading Apartment");
			progress.setMessage("Loading apartment details from our web service... Please wait");
			progress.show();
			List<String> pathSegs = getIntent().getData().getPathSegments();
			String apartmentId = pathSegs.get(pathSegs.size() - 1);
			resolveApartment(apartmentId);
			return;
		}
		if (progress != null) {
			progress.dismiss();
		}
		
		mapApartment = MapViewHelper.createMapView(this, llPlaceholder);
		mapApartment.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 250));
		mapApartment.setClickable(true);		
		mapApartment.setBuiltInZoomControls(true);
		mapApartment.setTraffic(true);
		MapController controller = mapApartment.getController();
		controller.setZoom(17);
		GeoPoint apartmentPoint = new GeoPoint((int)(apartment.getLatitude()*1E6), (int)(apartment.getLongitude()*1E6));
		controller.setCenter(apartmentPoint);
		TrivialOverlay apartmentOverlay = new TrivialOverlay(getResources().getDrawable(R.drawable.apartmentoverlay));
		apartmentOverlay.setPoint(apartmentPoint);
		mapApartment.getOverlays().add(apartmentOverlay);
		
		if (!apartment.isPublished()) {
			txtUnpublished.setVisibility(View.VISIBLE);
		}
		txtAddress.setText(apartment.getAddress());
		txtPrice.setText(Integer.toString(apartment.getPrice()));
		txtBedrooms.setText(Integer.toString(apartment.getBedrooms()));
		txtPhoneNumber.setText(apartment.getPhone());
		txtEmailAddress.setText(apartment.getEmail());
		chkAC.setChecked(apartment.isHasAC());
		chkParking.setChecked(apartment.isHasParking());
		chkLift.setChecked(apartment.isHasLift());
		
		String notes = apartment.getNotes();
		if (notes == null || notes.length() == 0) {
			txtNotes.setVisibility(View.GONE);
			txtNotesLabel.setVisibility(View.GONE);
		} else {
			txtNotes.setText(apartment.getNotes());
		}
		
		webStreetView.setWebViewClient(new WebViewClient());
		String mapsUrl = "http://maps.googleapis.com/maps/api/streetview?size=300x300&" +
				"location=" + apartment.getLatitude() + "," + apartment.getLongitude() +
				"&fov=90&pitch=0&sensor=false";
		Log.v("ApartmentDetails", mapsUrl);
		webStreetView.loadUrl(mapsUrl);
		
		if (apartment.hasPictures()) {
			picturesAdapter = new ImageGridAdapter(this);
			grdPictures.setAdapter(picturesAdapter);
			populatePictures();
		} else {
			grdPictures.setVisibility(View.GONE);
			txtPicturesLabel.setVisibility(View.GONE);
		}
		
		populateRating();
	}
	
	@Background
	protected void populateRating() {
		rating = new ApartmentRating(apartment.getObjectId());
		updateRatingBar();
	}
	
	@UiThread
	protected void updateRatingBar() {
		rtgApartmentRating.setRating(rating.getCurrentRating());
		txtNumRatings.setText(String.format("%d votes", rating.getNumRatings()));
	}
	
	@Background
	protected void populatePictures() {
		try {
			Bitmap[] pictures = apartment.getPictures();
			updatePicturesAdapter(pictures);
		} catch (ParseException e) {
			Log.w("ApartmentDetails", "Error retrieving pictures: " + e.getMessage());
		}
		
	}
	
	@ItemClick(R.id.grdPictures)
	protected void onPictureClicked(int position) {
		Bitmap bitmap = picturesAdapter.getImage(position);
		new ImageDisplayActivity_.IntentBuilder_(this).image(bitmap).start();
	}
	
	@UiThread
	protected void updatePicturesAdapter(Bitmap[] pictures) {
		for (Bitmap picture : pictures) {
			picturesAdapter.addImage(picture, false /*FIFO*/);
		}
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}
